package com.example.socket.server;

import com.example.socket.model.DataPackage;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Slf4j
public class MyNettyServerHandler extends SimpleChannelInboundHandler<DataPackage> {

    private String tmpDir = "d:\\tmp1\\";

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DataPackage dataPackage) throws Exception {
        int type = dataPackage.getType();
        if (type == 1){
            log.info("收到 hello 包: ");
            DataPackage dataPackage1 = new DataPackage();
            dataPackage1.setType(1);
            dataPackage1.setLength(0);
            dataPackage1.setValue("hello".getBytes(StandardCharsets.UTF_8));
            ctx.writeAndFlush(dataPackage1);
            return;
        }

        if (type == 2){
            //发data_ack
            byte[] value = dataPackage.getValue();
            ByteBuf byteBuf = Unpooled.copiedBuffer(value);
            int dataType = byteBuf.readInt();
            if (dataType==1){
                log.info("收到 数据块包 ");
                int valueLength = byteBuf.readInt();
                log.info("第一个data 包的数据 valueLength : "+ valueLength );
                byte[] bytes = new byte[valueLength];
                byteBuf.getBytes(byteBuf.readerIndex(), bytes);
                String str = new String(bytes, 0, valueLength, CharsetUtil.UTF_8);
                log.info("第一个data 包的数据 "+ str );
            }
            if (dataType==2){
                log.info("收到 文件块包 ");
                int valueLength = byteBuf.readInt();
                ByteBuf byteBuf1 = byteBuf.readBytes(valueLength);
                int filePackage = byteBuf1.readInt();
                if (filePackage==0x0101){
                    int fileNameLength = byteBuf1.readInt();
                    log.info("file name length :"+ fileNameLength );
                    byte[] bytes = new byte[fileNameLength];
                    byteBuf1.getBytes(byteBuf1.readerIndex(), bytes);
                    String fileName = new String(bytes, 0, fileNameLength,CharsetUtil.UTF_8);
                    log.info("fileName "+ fileName );
                    ByteBuf fileDataBuf = byteBuf1.readBytes(byteBuf1.readableBytes());
                    FileOutputStream outputStream = null;
                    try {
                        outputStream = new FileOutputStream(tmpDir+fileName);
                        outputStream.write(fileDataBuf.array());
                        outputStream.flush();
                        outputStream.close();
                        log.info("文件创建成功！");
                    } catch (IOException e) {
                        log.info("文件创建失败！");
                    }finally {
                        if (outputStream!=null){
                            outputStream.close();
                        }
                    }
                }else{
                    if (filePackage==0x0100) {
                        int fileNameLength = byteBuf1.readInt();
                        log.info("fileNameLength2:"+ fileNameLength );
                        byte[] bytes = new byte[fileNameLength];
                        byteBuf1.getBytes(byteBuf1.readerIndex(), bytes);
                        String fileName = new String(bytes, 0, fileNameLength,CharsetUtil.UTF_8);
                        log.info("fileName1:"+ fileName );
                        ByteBuf fileDataBuf = byteBuf1.readBytes(byteBuf1.readableBytes());
                        FileOutputStream outputStream = null;
                        try {
                            outputStream = new FileOutputStream(tmpDir + fileName);
                            outputStream.write(fileDataBuf.array());
                            outputStream.flush();
                            outputStream.close();
                            log.info("文件创建成功！");
                        } catch (IOException e) {
                            log.info("文件创建失败！");
                        } finally {
                            if (outputStream != null) {
                                outputStream.close();
                            }
                        }
                    }else{
                        int fileNameLength = byteBuf1.readInt();
                        log.info("fileNameLength2:"+fileNameLength);
                        ByteBuf byteBuf2 = byteBuf1.readBytes(fileNameLength);
                        /*String fileName = new String(byteBuf2.array(), CharsetUtil.UTF_8);
                        log.info("fileName2:"+fileName);*/
                        ByteBuf fileDataBuf = byteBuf1.readBytes(byteBuf1.readableBytes());
                        FileOutputStream outputStream = null;
                        try {
                            File f = new File(tmpDir);
                            File file = Objects.requireNonNull(f.listFiles())[0];
                            outputStream = new FileOutputStream(file,true);
                            outputStream.write(fileDataBuf.array());
                            outputStream.flush();
                            outputStream.close();
                            log.info("文件追加成功！");
                        } catch (IOException e) {
                            log.info("文件创建失败！");
                        } finally {
                            if (outputStream != null) {
                                outputStream.close();
                            }
                        }
                    }
                }
            }
            DataPackage dataPackage1 = new DataPackage();
            dataPackage1.setType(3);
            dataPackage1.setLength(0);
            dataPackage1.setValue("data_ack".getBytes(StandardCharsets.UTF_8));
            ctx.writeAndFlush(dataPackage1);
            return;
        }


        if (type == 4){
            //发finish
            log.info("收到 done 包: ");
            DataPackage dataPackage1 = new DataPackage();
            dataPackage1.setType(5);
            dataPackage1.setLength(0);
            dataPackage1.setValue("finish".getBytes(StandardCharsets.UTF_8));
            ctx.writeAndFlush(dataPackage1);
        }
    }
}
